<template>
  <div class="animate-fade-in">
    <!-- 导航栏 -->
    <nav class="glass shadow-sm">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center">
            <h1 class="text-xl font-bold text-gray-900">
              <i class="fas fa-gamepad mr-2"></i>
              游戏预约
            </h1>
          </div>
          <div class="flex items-center space-x-4">
            <span class="text-gray-600">
              <i class="fas fa-user mr-1"></i>
              {{ authStore.user?.nickname }}
            </span>
            <button 
              @click="toggleNotifications" 
              class="relative text-gray-600 hover:text-gray-900 transition-colors p-2"
            >
              <i class="fas fa-bell"></i>
              <span 
                v-if="unreadCount > 0" 
                class="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center"
              >
                {{ unreadCount > 99 ? '99+' : unreadCount }}
              </span>
            </button>
            <button 
              @click="$router.push('/my-appointments')" 
              class="btn-secondary"
            >
              <i class="fas fa-list mr-1"></i>
              我的预约
            </button>
            <button 
              @click="$router.push('/create')" 
              class="btn-primary"
            >
              <i class="fas fa-plus mr-1"></i>
              创建预约
            </button>
            <button 
              @click="handleLogout" 
              class="text-gray-600 hover:text-gray-900 transition-colors"
            >
              <i class="fas fa-sign-out-alt mr-1"></i>
              退出
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- 主要内容 -->
    <main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
      <!-- 筛选器 -->
      <div class="mb-6 glass rounded-lg p-4">
        <div class="flex flex-wrap gap-4 items-center">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">游戏类型</label>
            <select v-model="filter.category" class="input-field w-32">
              <option value="">全部</option>
              <option value="MOBA">MOBA</option>
              <option value="FPS">FPS</option>
              <option value="RPG">RPG</option>
              <option value="RTS">RTS</option>
              <option value="MMO">MMO</option>
              <option value="其他">其他</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">搜索</label>
            <input 
              type="text" 
              v-model="filter.search" 
              placeholder="搜索游戏或描述..."
              class="input-field w-48"
            >
          </div>
          <div class="flex items-end">
            <button @click="resetFilter" class="btn-primary">
              <i class="fas fa-refresh mr-1"></i>
              重置
            </button>
          </div>
        </div>
      </div>

      <!-- 预约列表 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" v-if="filteredAppointments.length">
        <div 
          v-for="appointment in filteredAppointments" 
          :key="appointment.id"
          class="glass rounded-lg shadow-lg p-6 space-y-4 hover-scale cursor-pointer animate-slide-up"
          @click="selectAppointment(appointment)"
        >
          <div class="flex justify-between items-start">
            <div>
              <span
                class="px-2 py-1 rounded-full text-sm"
                :class="getCategoryColor(appointment.category_name || appointment.category)"
              >
                {{ appointment.category_name || appointment.category }}
              </span>
              <h3 class="mt-2 text-lg font-semibold">{{ appointment.title }}</h3>
            </div>
            <span class="text-sm text-gray-500">{{ formatDate(appointment.created_at || appointment.createdAt) }}</span>
          </div>
          
          <p class="text-gray-600">{{ appointment.description }}</p>
          
          <div class="text-sm text-gray-500">
            创建人: <span class="font-medium">{{ appointment.creator_nickname || appointment.creator_username || appointment.creator }}</span>
          </div>

          <div class="flex justify-between items-center">
            <span class="text-sm text-gray-500">
              {{ appointment.current_players || appointment.currentPlayers }}/{{ appointment.max_players || appointment.maxPlayers }} 人
            </span>
            <button 
              @click.stop="openApplyModal(appointment)"
              :disabled="!canApply(appointment)"
              class="btn-success disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <i class="fas fa-user-plus mr-1"></i>
              {{ getApplyButtonText(appointment) }}
            </button>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-else class="text-center py-12">
        <i class="fas fa-search text-4xl text-gray-400 mb-4"></i>
        <p class="text-gray-500">没有找到符合条件的预约</p>
      </div>
    </main>

    <!-- 申请模态框 -->
    <div v-if="showApplyModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center p-4 z-50">
      <div class="glass rounded-lg max-w-md w-full p-6 space-y-4 animate-slide-up">
        <h3 class="text-lg font-semibold">申请加入 - {{ selectedAppointment?.title }}</h3>
        
        <form @submit.prevent="handleApply" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700">申请原因</label>
            <textarea 
              v-model="applyForm.reason" 
              class="input-field" 
              rows="3" 
              required
              placeholder="请简单介绍一下自己的游戏经验..."
            ></textarea>
          </div>
          
          <div v-if="applyError" class="text-red-600 text-sm">
            {{ applyError }}
          </div>
          
          <div class="flex justify-end space-x-4">
            <button 
              type="button" 
              @click="closeApplyModal"
              class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors"
            >
              取消
            </button>
            <button 
              type="submit" 
              :disabled="applyLoading"
              class="btn-primary disabled:opacity-50"
            >
              {{ applyLoading ? '提交中...' : '确认申请' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 通知下拉框 -->
    <div v-if="showNotifications" class="fixed inset-0 z-40" @click="closeNotifications">
      <div class="absolute top-16 right-4 w-80 max-h-96 glass rounded-lg shadow-lg p-4 overflow-y-auto z-50" @click.stop>
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-semibold">通知</h3>
          <button 
            v-if="notifications.some(n => !n.read)"
            @click="markAllAsRead"
            class="text-sm text-blue-600 hover:text-blue-800"
          >
            全部已读
          </button>
        </div>
        
        <div v-if="notifications.length === 0" class="text-center py-8 text-gray-500">
          <i class="fas fa-bell-slash text-2xl mb-2"></i>
          <p>暂无通知</p>
        </div>
        
        <div v-else class="space-y-3">
          <div 
            v-for="notification in notifications" 
            :key="notification.id"
            :class="[
              'p-3 rounded border cursor-pointer transition-colors',
              notification.read ? 'bg-gray-50 border-gray-200' : 'bg-blue-50 border-blue-200'
            ]"
            @click="markAsRead(notification.id)"
          >
            <div class="flex justify-between items-start mb-1">
              <h4 class="font-medium text-sm">{{ notification.title }}</h4>
              <span v-if="!notification.read" class="w-2 h-2 bg-blue-500 rounded-full"></span>
            </div>
            <p class="text-sm text-gray-600">{{ notification.content }}</p>
            <p class="text-xs text-gray-400 mt-1">{{ formatDateTime(notification.created_at) }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 预约详情弹窗 -->
    <div v-if="showDetailModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center p-4 z-50">
      <div class="glass rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto p-6 space-y-6 animate-slide-up">
        <div class="flex justify-between items-start">
          <h2 class="text-2xl font-bold text-gray-900">预约详情</h2>
          <button 
            @click="closeDetailModal"
            class="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <i class="fas fa-times text-xl"></i>
          </button>
        </div>

        <div v-if="detailLoading" class="text-center py-8">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
          <p class="mt-2 text-gray-600">加载中...</p>
        </div>

        <div v-else-if="appointmentDetail" class="space-y-6">
          <!-- 基本信息 -->
          <div class="bg-white bg-opacity-50 rounded-lg p-4">
            <h3 class="text-lg font-semibold mb-3 text-gray-900">基本信息</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <span class="text-sm text-gray-500">预约标题</span>
                <p class="font-medium text-gray-900">{{ appointmentDetail.title }}</p>
              </div>
              <div>
                <span class="text-sm text-gray-500">游戏名称</span>
                <p class="font-medium text-gray-900">{{ appointmentDetail.game_name }}</p>
              </div>
              <div>
                <span class="text-sm text-gray-500">创建人</span>
                <p class="font-medium text-gray-900">
                  {{ appointmentDetail.creator_nickname || appointmentDetail.creator_username }}
                </p>
              </div>
              <div>
                <span class="text-sm text-gray-500">预约时间</span>
                <p class="font-medium text-gray-900">{{ formatDateTime(appointmentDetail.scheduled_time) }}</p>
              </div>
              <div>
                <span class="text-sm text-gray-500">人数限制</span>
                <p class="font-medium text-gray-900">{{ appointmentDetail.current_players }}/{{ appointmentDetail.max_players }} 人</p>
              </div>
              <div>
                <span class="text-sm text-gray-500">状态</span>
                <span
                  :class="[
                    'px-3 py-1 rounded-full text-sm font-medium',
                    getStatusClass(appointmentDetail.status)
                  ]"
                >
                  {{ getStatusText(appointmentDetail.status) }}
                </span>
              </div>
            </div>
          </div>

          <!-- 预约描述 -->
          <div v-if="appointmentDetail.description" class="bg-white bg-opacity-50 rounded-lg p-4">
            <h3 class="text-lg font-semibold mb-3 text-gray-900">预约描述</h3>
            <p class="text-gray-700 whitespace-pre-wrap">{{ appointmentDetail.description }}</p>
          </div>

          <!-- 其他要求 -->
          <div v-if="appointmentDetail.requirements" class="bg-white bg-opacity-50 rounded-lg p-4">
            <h3 class="text-lg font-semibold mb-3 text-gray-900">参与要求</h3>
            <p class="text-gray-700 whitespace-pre-wrap">{{ appointmentDetail.requirements }}</p>
          </div>

          <!-- 联系方式 -->
          <div v-if="appointmentDetail.contact_info" class="bg-white bg-opacity-50 rounded-lg p-4">
            <h3 class="text-lg font-semibold mb-3 text-gray-900">联系方式</h3>
            <p class="text-gray-700">{{ appointmentDetail.contact_info }}</p>
          </div>

          <!-- 参与者列表 -->
          <div class="bg-white bg-opacity-50 rounded-lg p-4">
            <h3 class="text-lg font-semibold mb-3 text-gray-900">已通过的参与者</h3>
            <div v-if="appointmentDetail.participants && appointmentDetail.participants.length > 0" 
                 class="flex flex-wrap gap-2">
              <span 
                v-for="participant in appointmentDetail.participants" 
                :key="participant"
                class="px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-medium"
              >
                <i class="fas fa-user mr-1"></i>
                {{ participant }}
              </span>
            </div>
            <p v-else class="text-gray-500 text-sm">暂无参与者</p>
          </div>

          <!-- 操作按钮 -->
          <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200">
            <button 
              @click="closeDetailModal"
              class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors"
            >
              关闭
            </button>
            <button 
              v-if="canApply(appointmentDetail)"
              @click="openApplyModalFromDetail"
              class="btn-success"
            >
              <i class="fas fa-user-plus mr-1"></i>
              申请加入
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useAppointmentsStore } from '@/stores/appointments'
import { notificationAPI } from '@/services/api'

const router = useRouter()
const authStore = useAuthStore()
const appointmentsStore = useAppointmentsStore()

// 筛选器
const filter = ref({
  category: '',
  search: ''
})

// 申请相关
const showApplyModal = ref(false)
const selectedAppointment = ref(null)
const applyForm = ref({
  reason: ''
})
const applyError = ref('')
const applyLoading = ref(false)

// 通知相关
const showNotifications = ref(false)
const notifications = ref([])
const unreadCount = ref(0)

// 详情弹窗相关
const showDetailModal = ref(false)
const appointmentDetail = ref(null)
const detailLoading = ref(false)

// 计算属性
const filteredAppointments = computed(() => {
  return appointmentsStore.appointments
})

// 方法
const getCategoryColor = (category) => {
  const colors = {
    'MOBA': 'bg-blue-100 text-blue-800',
    'FPS': 'bg-red-100 text-red-800',
    'RPG': 'bg-green-100 text-green-800',
    'RTS': 'bg-purple-100 text-purple-800',
    'MMO': 'bg-yellow-100 text-yellow-800',
    '其他': 'bg-gray-100 text-gray-800'
  }
  return colors[category] || colors['其他']
}

const formatDate = (dateString) => {
  if (!dateString) return ''

  try {
    const date = new Date(dateString)
    const now = new Date()
    const diffTime = date.getTime() - now.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    if (diffDays === 0) {
      return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    } else if (diffDays === 1) {
      return '明天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    } else if (diffDays === 2) {
      return '后天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    } else {
      return date.toLocaleDateString('zh-CN', {
        month: 'numeric',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  } catch (error) {
    return dateString
  }
}

const formatDateTime = (dateString) => {
  if (!dateString) return ''
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}

const canApply = (appointment) => {
  const currentUser = authStore.user?.username
  return appointment.creator_username !== currentUser &&
         !appointment.participants.includes(currentUser) &&
         appointment.current_players < appointment.max_players &&
         !appointment.applications?.some(app => app.applicant_username === currentUser)
}

const getApplyButtonText = (appointment) => {
  const currentUser = authStore.user?.username

  if (appointment.creator_username === currentUser) return '我的预约'
  if (appointment.participants.includes(currentUser)) return '已加入'
  if (appointment.current_players >= appointment.max_players) return '已满员'
  if (appointment.applications?.some(app => app.applicant_username === currentUser)) return '已申请'

  return '申请加入'
}

const selectAppointment = async (appointment) => {
  await showAppointmentDetail(appointment.id)
}

// 详情弹窗相关方法
const showAppointmentDetail = async (appointmentId) => {
  try {
    detailLoading.value = true
    showDetailModal.value = true
    appointmentDetail.value = null

    const response = await appointmentAPI.getById(appointmentId)
    if (response.success !== false) {
      appointmentDetail.value = response.data || response
    }
  } catch (error) {
    console.error('获取预约详情失败:', error)
  } finally {
    detailLoading.value = false
  }
}

const closeDetailModal = () => {
  showDetailModal.value = false
  appointmentDetail.value = null
  detailLoading.value = false
}

const openApplyModalFromDetail = () => {
  if (appointmentDetail.value && canApply(appointmentDetail.value)) {
    closeDetailModal()
    openApplyModal(appointmentDetail.value)
  }
}

const openApplyModal = (appointment) => {
  if (!canApply(appointment)) return
  
  selectedAppointment.value = appointment
  showApplyModal.value = true
  applyForm.value.reason = ''
  applyError.value = ''
}

const closeApplyModal = () => {
  showApplyModal.value = false
  selectedAppointment.value = null
  applyForm.value.reason = ''
  applyError.value = ''
}

const handleApply = async () => {
  applyError.value = ''
  applyLoading.value = true

  try {
    const result = await appointmentsStore.applyToAppointment(
      selectedAppointment.value.id,
      applyForm.value.reason
    )

    if (result.success) {
      closeApplyModal()
      alert(result.message)
      // 刷新预约列表
      await loadAppointments()
    } else {
      applyError.value = result.message
    }
  } catch (err) {
    applyError.value = '申请失败，请重试'
  } finally {
    applyLoading.value = false
  }
}

const resetFilter = async () => {
  filter.value = {
    category: '',
    search: ''
  }
  await loadAppointments()
}

const handleLogout = async () => {
  await authStore.logout()
  router.push('/login')
}

// 通知相关方法
const toggleNotifications = () => {
  showNotifications.value = !showNotifications.value
  if (showNotifications.value) {
    loadNotifications()
  }
}

const closeNotifications = () => {
  showNotifications.value = false
}

const loadNotifications = async () => {
  try {
    const response = await notificationAPI.getNotifications()
    if (response.success !== false) {
      notifications.value = response.data || response
    }
  } catch (error) {
    console.error('获取通知失败:', error)
  }
}

const loadUnreadCount = async () => {
  try {
    const response = await notificationAPI.getUnreadCount()
    if (response.success !== false) {
      unreadCount.value = response.data?.count || 0
    }
  } catch (error) {
    console.error('获取未读通知数量失败:', error)
  }
}

const markAsRead = async (notificationId) => {
  try {
    const response = await notificationAPI.markAsRead(notificationId)
    if (response.success !== false) {
      // 更新本地通知状态
      const notification = notifications.value.find(n => n.id === notificationId)
      if (notification && !notification.read) {
        notification.read = true
        unreadCount.value = Math.max(0, unreadCount.value - 1)
      }
    }
  } catch (error) {
    console.error('标记通知为已读失败:', error)
  }
}

const markAllAsRead = async () => {
  try {
    const response = await notificationAPI.markAllAsRead()
    if (response.success !== false) {
      // 更新本地通知状态
      notifications.value.forEach(notification => {
        notification.read = true
      })
      unreadCount.value = 0
    }
  } catch (error) {
    console.error('标记所有通知为已读失败:', error)
  }
}

// 加载预约列表
const loadAppointments = async () => {
  const params = {}

  if (filter.value.category) {
    params.category_id = filter.value.category
  }

  if (filter.value.search) {
    params.keyword = filter.value.search
  }

  await appointmentsStore.fetchAppointments(params)
}

// 监听筛选条件变化
watch(filter, async () => {
  await loadAppointments()
}, { deep: true })

onMounted(async () => {
  await authStore.initAuth()
  await loadAppointments()
  await loadUnreadCount()
})
</script>
